package com.luomo.wenyuan.modules.wenyuan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luomo.wenyuan.common.utils.PageUtils;
import com.luomo.wenyuan.common.utils.Query;
import com.luomo.wenyuan.modules.wenyuan.dao.TOrderBookDao;
import com.luomo.wenyuan.modules.wenyuan.dao.TOrderDao;
import com.luomo.wenyuan.modules.wenyuan.entity.TBookEntity;
import com.luomo.wenyuan.modules.wenyuan.entity.TOrderBookEntity;
import com.luomo.wenyuan.modules.wenyuan.entity.TOrderEntity;
import com.luomo.wenyuan.modules.wenyuan.service.TBookService;
import com.luomo.wenyuan.modules.wenyuan.service.TOrderService;
import com.luomo.wenyuan.modules.wenyuan.vo.TPurchaseBookVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("tOrderService")
public class TOrderServiceImpl extends ServiceImpl<TOrderDao, TOrderEntity> implements TOrderService {

    @Autowired
    private TOrderBookDao tOrderBookDao;

    @Autowired
    private TBookService tBookService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String status = (String) params.get("status");
        IPage<TOrderEntity> page = this.page(
                new Query<TOrderEntity>().getPage(params),
                new QueryWrapper<TOrderEntity>()
                        .eq(StrUtil.isNotEmpty(status), "order_status", Integer.valueOf(status))
        );

        return new PageUtils(page);
    }

    @Override
    public String getBookNameStrByOrderId(int orderId) {
        List<String> booksStr = new ArrayList<>();
        List<TOrderBookEntity> books = tOrderBookDao.getByOrderId(orderId);
        for (TOrderBookEntity book : books) {
            TBookEntity tBookEntity = tBookService.getById(book.getBookId());
            booksStr.add(tBookEntity.getName());
        }
        return StrUtil.join(",", booksStr);
    }

    @Override
    public List<TPurchaseBookVo> getBookListByOrderId(int orderId) {
        List<TPurchaseBookVo> bookVos = new ArrayList<>();
        TPurchaseBookVo bookVo;
        List<TOrderBookEntity> books = tOrderBookDao.getByOrderId(orderId);
        for (TOrderBookEntity book : books) {
            TBookEntity tBookEntity = tBookService.getById(book.getBookId());
            bookVo = new TPurchaseBookVo();
            BeanUtil.copyProperties(tBookEntity, bookVo);
            bookVo.setNum(book.getNum());
            bookVos.add(bookVo);
        }
        return bookVos;
    }

}